package bat.iog.hytool.excel;


import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;

import java.io.*;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

public class ExcelHandler<T> {

    /**
     * Excel sheet最大行数，默认65536
     */
    public static final int sheetSize = 65536;
    /**
     * 工作薄对象
     */
    private Workbook wb;
    /**
     * 工作表对象
     */
    private Sheet sheet;
    /**
     * 样式列表
     */
    private Map<String, CellStyle> styles;
    /**
     * 获取ExcelBean实例
     */
    private ExcelBean<Object> ebean;

    /**
     * 导入excel数据
     * @param is
     * @return
     * @throws Exception
     */
    public List<T> importExcel(InputStream is) throws Exception
    {
        return importExcel(null, is);
    }

    public List<T> importExcel(String sheetName, InputStream is) throws Exception{
        ebean.type = Excel.Type.IMPORT;
        this.wb = WorkbookFactory.create(is);
        List<T> list = new ArrayList<>();
        Sheet sheet = null;
        if (sheetName != null && !sheetName.equals("")) {
            // 如果指定sheet名,则取指定sheet中的内容.
            sheet = wb.getSheet(sheetName);
        }
        else {
            // 如果传入的sheet名不存在则默认指向第1个sheet.
            sheet = wb.getSheetAt(0);
        }

        if (sheet == null) {
            throw new IOException("文件sheet不存在");
        }

        //获取excel数据行数
        int rows = sheet.getPhysicalNumberOfRows();
        
        if (rows > 1) {
            //定义一个map用于存放excel列的序号和表头列名
            Map<String, Integer> excelHeaderValueColMap = new HashMap<>();
            setHeadCellMap(excelHeaderValueColMap, sheet);
            
            //定义一个map用于存放列的序号和实体类的属性
            Map<Integer, Field> fieldsMap = new HashMap<>();
            setFieldsMap(fieldsMap, excelHeaderValueColMap);
            
            //遍历excel数据行
            for (int i = 1; i < rows; i++)
            {
                //从第2行开始取数据,默认第一行是表头.
                Row row = sheet.getRow(i);
                //excel导入对应的类对象
                T entity = null;
                //为对象赋值
                setEntityValue(entity, row, fieldsMap);
                list.add(entity);
            }
        }
        return list;
    }

    /**
     * 为对象赋值
     * @param entity
     * @param row
     * @param fieldsMap
     * @throws Exception
     */
    public void setEntityValue(T entity, Row row, Map<Integer, Field> fieldsMap) throws Exception {
        for (Map.Entry<Integer, Field> entry : fieldsMap.entrySet()) {
            //获取excel单元格的值
            Object val = this.getCellValue(row, entry.getKey());
            
            entity = (entity == null ? (T) ebean.clazz.newInstance() : entity);
            //得到对应列的field
            Field field = entry.getValue();
            //取得类型,并根据对象类型设置值.
            Class<?> fieldType = field.getType();
            
            //将从excel中取出的数据装换为相应属性的类型
            convertValType(val, fieldType);
            
            Excel attr = field.getAnnotation(Excel.class);
            //通过反射将相应属性的值写入对象中
            String propertyName = field.getName();
            if (attr.targetAttr() != null) {
                propertyName = field.getName() + "." + attr.targetAttr();
            }
            else if (attr.readConverterExp() != null)
            {
                val = reverseByExp(String.valueOf(val), attr.readConverterExp());
            }
            String[] names = propertyName.split("\\.");
            
            //Object object = entity;
            for (int i = 0; i < names.length; i++)
            {
                if (i < names.length - 1)
                {
                    String getterMethodName = "get" + capitalize(names[i]);
                    
                    //entity = invokeMethod(entity, getterMethodName, new Class[] {}, new Object[] {});
                }
                else
                {
                    String setterMethodName = "set" + capitalize(names[i]);
                    //invokeMethodByName(object, setterMethodName, new Object[] { value });
                }
            }
            //反射
        }
    }
    
    public static <E> E invokeMethod(Object obj, String methodName, Class<?>[] parameterTypes, Object[] args) {
        if (obj == null || methodName == null) {
            return null;
        }
        Method method = getMethodByMethodName(obj, methodName, parameterTypes);
        try {
            return (E) method.invoke(obj, args);
           
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过方法名获取到方法
     * @return
     */
    public static Method getMethodByMethodName(final Object obj, final String methodName, final Class<?>... parameterTypes){
        // 为空不报错。直接返回 null
        if (obj == null || methodName == null) {
            return null;
        }
        for (Class<?> searchType = obj.getClass();  searchType != Object.class; searchType = searchType.getSuperclass()) {
            try {
                Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
                method.setAccessible(true);
                return method;
            } catch (NoSuchMethodException e) {
                continue;
            }
        }
        return null;
    }
    
    /**
     * 反射default方法
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    private Object invokeDefaultMethod(Object proxy, Method method, Object[] args) throws Throwable {
        final Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class.getDeclaredConstructor(Class.class, int.class);
        
        if (!constructor.isAccessible()) {
            constructor.setAccessible(true);
        }
        final Class<?> declaringClass = method.getDeclaringClass();
        
        return constructor.newInstance(declaringClass, MethodHandles.Lookup.PRIVATE)
                         .unreflectSpecial(method, declaringClass)
                         .bindTo(proxy)
                         .invokeWithArguments(args);
    }

    /**
     * Backport of java.lang.reflect.Method#isDefault()
     */
    private boolean isDefaultMethod(Method method) {
        return ((method.getModifiers() & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)) == Modifier.PUBLIC)
                && method.getDeclaringClass().isInterface();
    }
    
    /**
     * 首字母大写
     */
    public String capitalize(String str){
        char[] ch = str.toCharArray();
        if (ch[0] >= 'a' && ch[0] <= 'z') {
            ch[0] = (char) (ch[0] - 32);
        }
        return new String(ch); 
    }
    
    /**
     * 反向解析值 男=0,女=1,未知=2
     */
    public static String reverseByExp(String propertyValue, String converterExp) throws Exception
    {
        try
        {
            String[] convertSource = converterExp.split(",");
            for (String item : convertSource)
            {
                String[] itemArray = item.split("=");
                if (itemArray[1].equals(propertyValue))
                {
                    return itemArray[0];
                }
            }
        }
        catch (Exception e)
        {
            throw e;
        }
        return propertyValue;
    }
    
    /**
     * 将数据装换为相应的类型
     */
    public void convertValType(Object val, Class<?> fieldType){
        if (String.class == fieldType) {
            
        } else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {
            
        } else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {
            
        } else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {
            
        } else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {
            
        } else if (BigDecimal.class == fieldType) {
            
        } else if (Date.class == fieldType) {
            
        }
    }
    
    /**
     * 存放excel列的序号和列名.
     * @param cellMap
     * @param sheet
     */
    public void setHeadCellMap(Map<String, Integer> cellMap, Sheet sheet) {
        // 获取表头
        Row heard = sheet.getRow(0);
        for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) {
            Cell cell = heard.getCell(i);
            if (cell != null) {
                String value = this.getCellValue(heard, i).toString();
                cellMap.put(value, i);
            }
            else {
                cellMap.put(null, i);
            }
        }
    }

    public void setFieldsMap(Map<Integer, Field> fieldsMap, Map<String, Integer> cellMap) {
        // 有数据时才处理 得到类的所有field.
        Field[] allFields = ebean.clazz.getDeclaredFields();
        for (int col = 0; col < allFields.length; col++)
        {
            Field field = allFields[col];
            Excel attr = field.getAnnotation(Excel.class);
            if (attr != null && (attr.type() == Excel.Type.ALL || attr.type() == ebean.type))
            {
                // 设置类的私有字段属性可访问.
                field.setAccessible(true);
                Integer column = cellMap.get(attr.name());
                fieldsMap.put(column, field);
            }
        }
    }
    
    /**
     * 获取单元格值
     * @param row 获取的行
     * @param column 获取单元格列号
     * @return 单元格值
     */
    public Object getCellValue(Row row, int column)
    {
        if (row == null)
        {
            return row;
        }
        Object val = "";
        try
        {
            Cell cell = row.getCell(column);
            if (cell != null)
            {
                if (cell.getCellTypeEnum() == CellType.NUMERIC || cell.getCellTypeEnum() == CellType.FORMULA)
                {
                    val = cell.getNumericCellValue();
                    if (HSSFDateUtil.isCellDateFormatted(cell))
                    {
                        val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
                    }
                    else
                    {
                        if ((Double) val % 1 > 0)
                        {
                            val = new DecimalFormat("0.00").format(val);
                        }
                        else
                        {
                            val = new DecimalFormat("0").format(val);
                        }
                    }
                }
                else if (cell.getCellTypeEnum() == CellType.STRING)
                {
                    val = cell.getStringCellValue();
                }
                else if (cell.getCellTypeEnum() == CellType.BOOLEAN)
                {
                    val = cell.getBooleanCellValue();
                }
                else if (cell.getCellTypeEnum() == CellType.ERROR)
                {
                    val = cell.getErrorCellValue();
                }

            }
        }
        catch (Exception e)
        {
            return val;
        }
        return val;
    }

    
    
    
    /**
     * 导出excel模板
     */
    public void exportExcelTemplate() {
        exportExcel();
    } 
    
    /**
     * 导出excel
     */
    public void exportExcel() {
        // 取出一共有多少个sheet.
        double sheetNo = Math.ceil(ebean.list.size() / sheetSize);
        for (int index = 0; index <= sheetNo; index++) {
            //创建工作表
            createSheet(sheetNo, index);
            //创建一行
            Row row = sheet.createRow(0);
            int column = 0;
            //excel添加表头
            for (Object[] os : ebean.fields) {
                Excel excel = (Excel) os[1];
                // 创建表头单元格
                this.createCell(excel, row, column++);
            }
            if (Excel.Type.EXPORT.equals(ebean.type)) {
                fillExcelData(index, row);
            }
            OutputStream out = null;
            
            try {
                out = new FileOutputStream(ebean.getAbsoluteFile(ebean.fileNmae));
                wb.write(out);
            } catch (IOException e) {
                e.printStackTrace();
            } 
            finally 
            {
                if (wb != null)
                {
                    try
                    {
                        wb.close();
                    }
                    catch (IOException e1)
                    {
                        e1.printStackTrace();
                    }
                }
                if (out != null)
                {
                    try
                    {
                        out.close();
                    }
                    catch (IOException e1)
                    {
                        e1.printStackTrace();
                    }
                }
            }
        }
    }
    
    //======================================================================创建Excel start============================================================================
    /**
     * 创建一个工作薄
     */
    private void createWorkbook() {
        this.wb = new SXSSFWorkbook(500);
    }

    /**
     * 创建工作表
     * @param sheetNo sheet数量
     * @param index 序号
     */
    private void createSheet(double sheetNo, int index) {
        this.sheet = wb.createSheet();
        this.styles = createStyles(wb);
        // 设置工作表的名称.
        if (sheetNo == 0) {
            wb.setSheetName(index, ebean.sheetName);
        }
        else {
            wb.setSheetName(index, ebean.sheetName + index);
        }
    }

    /**
     * 创建整体表格样式
     * @param wb 工作薄对象
     * @return 样式列表
     */
    private Map<String, CellStyle> createStyles(Workbook wb) {
        // 写入各条记录,每条记录对应excel表中的一行
        Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
        CellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderRight(BorderStyle.THIN);
        style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderLeft(BorderStyle.THIN);
        style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderTop(BorderStyle.THIN);
        style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderBottom(BorderStyle.THIN);
        style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        Font dataFont = wb.createFont();
        dataFont.setFontName("Arial");
        dataFont.setFontHeightInPoints((short) 10);
        style.setFont(dataFont);
        styles.put("data", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        Font headerFont = wb.createFont();
        headerFont.setFontName("Arial");
        headerFont.setFontHeightInPoints((short) 10);
        headerFont.setBold(true);
        headerFont.setColor(IndexedColors.WHITE.getIndex());
        style.setFont(headerFont);
        styles.put("header", style);

        return styles;
    }

    /**
     * 创建单元格
     */
    private Cell createCell(Excel attr, Row row, int column)
    {
        // 创建列
        Cell cell = row.createCell(column);
        // 写入列信息
        cell.setCellValue(attr.name());
        setDataValidation(attr, row, column);
        cell.setCellStyle(styles.get("header"));
        return cell;
    }

    /**
     * 设置表格的样式 如提示，下拉框等
     */
    private void setDataValidation(Excel attr, Row row, int column) {
        if (attr.name().indexOf("注：") >= 0) {
            sheet.setColumnWidth(column, 6000);
        } else {
            // 设置列宽
            sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
            row.setHeight((short) (attr.height() * 20));
        }
        // 如果设置了提示信息则鼠标放上去提示.
        if (attr.prompt() != null && attr.prompt() != "") {
            // 这里默认设了2-101列提示.
            setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column);
        }
        // 如果设置了combo属性则本列只能选择不能输入
        if (attr.combo().length > 0) {
            // 这里默认设了2-101列只能选择不能输入.
            setXSSFValidation(sheet, attr.combo(), 1, 100, column, column);
        }
    }
    /**
     * 设置 POI XSSFSheet 单元格提示
     *
     * @param sheet 表单
     * @param promptTitle 提示标题
     * @param promptContent 提示内容
     * @param firstRow 开始行
     * @param endRow 结束行
     * @param firstCol 开始列
     * @param endCol 结束列
     */
    private void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow, int firstCol, int endCol) {
        DataValidationHelper helper = sheet.getDataValidationHelper();
        DataValidationConstraint constraint = helper.createCustomConstraint("DD1");
        CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
        DataValidation dataValidation = helper.createValidation(constraint, regions);
        dataValidation.createPromptBox(promptTitle, promptContent);
        dataValidation.setShowPromptBox(true);
        sheet.addValidationData(dataValidation);
    }

    /**
     * 设置某些列的值只能输入预制的数据,显示下拉框.
     *
     * @param sheet 要设置的sheet.
     * @param textlist 下拉框显示的内容
     * @param firstRow 开始行
     * @param endRow 结束行
     * @param firstCol 开始列
     * @param endCol 结束列
     * @return 设置好的sheet.
     */
    private void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) {
        DataValidationHelper helper = sheet.getDataValidationHelper();
        // 加载下拉列表内容
        DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist);
        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
        CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
        // 数据有效性对象
        DataValidation dataValidation = helper.createValidation(constraint, regions);
        // 处理Excel兼容性问题
        if (dataValidation instanceof XSSFDataValidation) {
            dataValidation.setSuppressDropDownArrow(true);
            dataValidation.setShowErrorBox(true);
        } else {
            dataValidation.setSuppressDropDownArrow(false);
        }
        sheet.addValidationData(dataValidation);
    }

    /**
     * 填充excel数据
     *
     * @param index 序号
     * @param row 单元格行
     */
    public void fillExcelData(int index, Row row)
    {
        int startNo = index * sheetSize;
        int endNo = Math.min(startNo + sheetSize, ebean.list.size());
        for (int i = startNo; i < endNo; i++)
        {
            row = sheet.createRow(i + 1 - startNo);
            // 得到导出对象.
            //T vo = (T) list.get(i);
            int column = 0;
            for (Object[] os : ebean.fields)
            {
                Field field = (Field) os[0];
                Excel excel = (Excel) os[1];
                // 设置实体类私有属性可访问
                field.setAccessible(true);
                this.addCell(excel, row, field, column++);
            }
        }
    }
    
    /**
     * 添加单元格
     */
    public Cell addCell(Excel attr, Row row, Field field, int column)
    {
        Cell cell = null;
        try
        {
            // 设置行高
            row.setHeight((short) (attr.height() * 20));
            // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
            if (attr.isExport())
            {
                // 创建cell
                cell = row.createCell(column);
                cell.setCellStyle(styles.get("data"));

                // 用于读取对象中的属性
                Object value = ebean.getTargetValue(ebean.clazz, field, attr);
                String dateFormat = attr.dateFormat();
                String readConverterExp = attr.readConverterExp();
                if (dateFormat != null && value != null)
                {
                    //cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date) value));
                }
                else if (readConverterExp != null && value != null)
                {
                    //cell.setCellValue(convertByExp(String.valueOf(value), readConverterExp));
                }
                else
                {
                    // 设置列类型
                    setCellVo(value, attr, cell);
                }
            }
        }
        catch (Exception e)
        {
            System.err.println("导出Excel失败{}" + e);
        }
        return cell;
    }
    
    /**
     * 设置单元格数据
     *
     * @param value 单元格值
     * @param attr 注解相关
     * @param cell 单元格信息
     */
    public void setCellVo(Object value, Excel attr, Cell cell)
    {
        if (Excel.ColumnType.STRING == attr.cellType())
        {
            cell.setCellType(CellType.NUMERIC);
            cell.setCellValue(value == null ? attr.defaultValue() : value + attr.suffix());
        }
        else if (Excel.ColumnType.NUMERIC == attr.cellType())
        {
            cell.setCellType(CellType.NUMERIC);
            cell.setCellValue(Integer.parseInt(value + ""));
        }
    }
    //======================================================================创建Excel end============================================================================
}
